package ch.kerbtier.malurus.updaters;

import groovy.lang.Binding;
import groovy.util.GroovyScriptEngine;
import groovy.util.ResourceException;
import groovy.util.ScriptException;

import java.io.File;
import java.io.IOException;

import ch.kerbtier.malurus.Component;
import ch.kerbtier.malurus.RequestContext;
import ch.kerbtier.malurus.UpdateProvider;
import ch.kerbtier.malurus.Updater;

public class GroovyUpdateProvider implements UpdateProvider {
	private String postfix;
	private GroovyScriptEngine engine;
	private File path;

	public GroovyUpdateProvider(String path, String postfix) {
		this.postfix = postfix;
		this.path = new File(path);

		String[] roots = new String[] { path };

		try {
			engine = new GroovyScriptEngine(roots);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public Updater getUpdater(String component, String realisation) {
		String name = component + (realisation == null ? "" : "->" + realisation) + postfix;

		File f = new File(path, name);
		if (f.exists()) {
			return new GroovyUpdater(name, this);
		}
		return null;
	}

	public GroovyScriptEngine getEngine() {
		return engine;
	}

	public class GroovyUpdater implements Updater {
		private String name;
		private GroovyUpdateProvider provider;

		public GroovyUpdater(String name, GroovyUpdateProvider provider) {
			this.name = name;
			this.provider = provider;
		}

		public void update(Component component, RequestContext requestContext) {
			if (component.isVisible()) {
				final Binding binding = new Binding();

				binding.setVariable("request", requestContext.getRequest());
				binding.setVariable("response", requestContext.getResponse());
				binding.setVariable("subject", component);
				try {
					provider.getEngine().run(name, binding);
				} catch (ResourceException e) {
					e.printStackTrace();
				} catch (ScriptException e) {
					e.printStackTrace();
				} catch (Throwable e) {
					e.printStackTrace();
				}

			}
		}
	}
}
